<?php
class Accueil extends FrontEnd_Controller {

    function Accueil() {
        parent::FrontEnd_Controller();
        $this->load->helper('cookie');
        $this->load->model('Accueil_m');
        $this->load->model('Actualite_m');
        $this->load->model('Admin_m');
        $this->load->helper('date');
        $this->load->library('form_validation');
        $this->_data['error'] ='';
        $this->load->library('email');
        $this->_data['is_sidebar'] =true;
    }

    function index() {
        $this->_data['is_sidebar'] =false;
        $this->display_view('accueil/accueil');
    }
    function paiement_zoo_market(){
        is_user();

              	$user=  $this->Admin_m->get_admin_details($this->session->userdata('user_id'));
              	$user_email=$user->row()->email;
              	$total=$this->session->userdata('zoo_montant');
                if($this->session->userdata('vip')!="") $vip=1;
                else $vip=0;
              	$data = array(
                        'idclient'=>$this->session->userdata('user_id'),
                        'dat'=>time(),   
                        'montant'=>$total,
                        'adr'=>$this->session->userdata('zoo_adr'),
                        'id_livraison' => $this->session->userdata('zoo_livraison'),
                        'postale' => $this->session->userdata('zoo_postale'),
                        'ville'  => $this->session->userdata('zoo_ville'),
	                    'status' => 'Pas encore fini',
	                    'method'=>'1'
	                    );
              $query= $this->Accueil_m->add_commande($data);
              if($query){    
          	   	$data1 = array(
                        'idclient'=>$this->session->userdata('user_id'),
	                    );
	         $commande= $this->Accueil_m->get_my_commande($data1);
	         $produit=$this->cart->contents();
	         foreach ($produit as $aRow): 
	          $data_produit=array(
	          	'quantite'=>$aRow['qty'],
	          	'idcommande'=>$commande['id'], 
	          	'idproduit'=>$aRow['id'],   
	          	);
	          $query_produit= $this->Accueil_m->add_detail_commande($data_produit);	
	         endforeach;
 $this->cart->destroy();
redirect("https://www.bluepaid.com/in.php?&id_boutique=15555www&id_client=105230&montant=".$total."&devise=EUR&langue=FR&email_client=".$user_email."&divers=zoo|".$commande['id']."|".$vip);
              
          }
              
    }
    
    //register user//
    function register() {
        /*Captcha*/
        //$this->load->view('accueil/register_success');
        $expiration_period = time()-1800;
        $this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration_period);
        $this->load->plugin('captcha');
        $vals = array(
        'word'         => strtoupper(random_string('alnum',6)),
        'img_path'     => './assets/captcha/',
        'img_url'     => base_url().'assets/captcha/',
        'font_path'     => base_url().'system/fonts/texb.ttf',
        'img_width'     => '150',
        'img_height' => 32,
        'expiration' => 300
        );

        $cap = create_captcha($vals);

        $cap_save = array(
        'captcha_id'    => '',
        'captcha_time'    => $cap['time'],
        'ip_address'    => $this->input->ip_address(),
        'word'            => $cap['word']
        );
        $query = $this->db->insert_string('captcha', $cap_save);
        $this->db->query($query);
        $data['captcha_img'] = $cap['image'];
        /*End of captcha*/

        $config['charset'] = 'utf-8';
        $config['wordwrap'] = TRUE;
        $config['mailtype'] = 'html';

        $this->email->initialize($config);
        $data['date_error']=FALSE;
        if ($this->input->post('register')) {
            $formVal = array(
            array(
            'field' => 'user_name',
            'Label' => 'User name',
            'rules' => 'required|callback_check_exist_username'
            ),
            array(
            'field' => 'reg_email',
            'Label' => 'Email',
            'rules' => 'required|valid_email|callback_check_exist_email'
            ),
            array(
            'field' => 'reg_password',
            'Label' => 'Password',
            'rules' => 'required|matches[confirm_password]|min_length[5]'
            ),
            array(
            'field' => 'confirm_password',
            'Label' => 'Confirm Password',
            'rules' => 'required'
            ),
            array(
            'field' => 'first_name',
            'Label' => 'First name',
            'rules' => 'required'
            ),
            array(
            'field' => 'last_name',
            'Label' => 'Last name',
            'rules' => 'required'
            ),
            array(
            'field' => 'display_name',
            'Label' => 'Display name',
            'rules' => 'required'
            ),
            array(
            'field' => 'phone',
            'Label' => 'Phone number',
            'rules' => 'required|min_length[10]'
            ),
            array(
            'field' => 'mobile',
            'Label' => 'Mobile number',
            'rules' => 'required|min_length[10]'
            )
            ,
            array(
            'field' => 'captcha',
            'Label' => 'Picture letters',
            'rules' => 'required|max_length[6]|callback_is_correct_captcha'
            )
            );
            $this->form_validation->set_rules($formVal);
            
            $birthday = $this->input->post('birth_year') . '-' . $this->input->post('birth_month') . '-' . $this->input->post('birth_date') . ' ' . '06:00';
            $dob_long = human_to_unix($birthday);
            if($dob_long>now()){
                $data['date_error']='Sélection de date non valide';    
            }
            $data['selected_day'] = $this->input->post('birth_date'); 
            $data['selected_month'] = $this->input->post('birth_month'); 
            $data['selected_year'] = $this->input->post('birth_year');
            if ($this->form_validation->run() === TRUE && $dob_long<now()) {
                $image_path = './assets/avatar';
                $thumb_path = $image_path . '/images';
                $config = array(
                'allowed_types' => "jpg|jpeg|gif|png",
                'upload_path' => $image_path,
                'max_size' => 10000,
                'encrypt_name' =>TRUE
                );
                $this->load->library('upload', $config);

                if ($this->upload->do_upload()) {
                    $upload_info = $this->upload->data();
                    $config = array(
                    'source_image' => $upload_info['full_path'], //get original image
                    'new_image' => $thumb_path, //save as new image //need to create thumbs first
                    'maintain_ratio' => true,
                    'width' => 300,
                    'height' => 200
                    );
                    $this->load->library('image_lib', $config); //load library
                    $this->image_lib->resize(); //do whatever specified in config
                    delete_pro_file($upload_info['full_path']);
                    $email = $this->input->post('reg_email');
                    $password = $this->input->post('reg_password');
                    $confirm_password = $this->input->post('confirm_password');
                    $created_on = now();
                    $data_user = array('email' => $email,
                    'password' => md5($password),
                    'group_id' => 3,
                    'active' => '0',
                    'created_on' => $created_on,
                    'username' => $this->input->post('user_name')
                    );
                    $this->Accueil_m->register_user($data_user);

                    $query_id_max = $this->Accueil_m->get_user_id_max();
                    $user = $query_id_max->row();
                    $user_id = $user->new_id;
                    $display_name = $this->input->post('display_name');

                    $data_profile = array('user_id' => $user_id,
                    'display_name' => ucwords(strtolower($display_name)),
                    'first_name' => ucwords(strtolower($this->input->post('first_name'))),
                    'last_name' => ucwords(strtolower($this->input->post('last_name'))),
                    'company' => ucwords(strtolower($this->input->post('company'))),
                    'dob' => $dob_long,
                    'gender' => $this->input->post('gender'),
                    'phone' => $this->input->post('phone'),
                    'mobile' => $this->input->post('mobile'),
                    'address' => ucwords(strtolower($this->input->post('address'))),
                    'gravatar' => $upload_info['file_name']
                    );
                    $this->Accueil_m->register_profile($data_profile);

//                    $this->Accueil_m->get_user($email,  md5($password));
//                    $this->session->set_userdata('display_name', $display_name);
//                    $this->session->set_userdata('group_id', '3');
//                    $this->session->set_userdata('user_id', $user_id);

                    //send mail
                    $From = 'administrator@lehu.com';
                    $this->email->from($From, 'Lehu');
                    $this->email->to($this->input->post('reg_email'));
                    $this->email->subject("s'inscrire dans Lehu");
                    $message = 'Hello ' . $this->input->post('display_name').".<p> - Vous, ou quelqu'un en utilisant cette adresse e-mail pour vous inscrire sur le site: Lehu.</p>
                           <p> - Faire en sorte que vos abonnés, s'il vous plaît cliquer ici pour valider: <a href='". site_url('accueil/activate_user').'/'.$user_id."'>Confirmer</a> </p>
                              Cordialement,";
                    $this->email->message($message);

//                    echo $this->input->post('reg_email');
//                    echo $this->input->post('display_name');
//                    echo $message;die;
                    $this->email->send();
                    //end send

                    $this->load->view('accueil/register_success');
                } else {
                    $birthday = $this->input->post('birth_year') . '-' . $this->input->post('birth_month') . '-' . $this->input->post('birth_date') . ' ' . '06:00';
                    $dob_long = human_to_unix($birthday);
                    $email = $this->input->post('reg_email');
                    $password = $this->input->post('reg_password');
                    $confirm_password = $this->input->post('confirm_password');
                    $created_on = now();
                    $data_user = array('email' => $email,
                    'password' => md5($password),
                    'group_id' => 3,
                    'active' => '0',
                    'created_on' => $created_on,
                    'username' => $this->input->post('user_name')
                    );
                    $this->Accueil_m->register_user($data_user);

                    $query_id_max = $this->Accueil_m->get_user_id_max();
                    $user = $query_id_max->row();
                    $user_id = $user->new_id;
                    $display_name = $this->input->post('display_name');

                    $data_profile = array('user_id' => $user_id,
                    'display_name' => ucwords(strtolower($display_name)),
                    'first_name' => ucwords(strtolower($this->input->post('first_name'))),
                    'last_name' => ucwords(strtolower($this->input->post('last_name'))),
                    'company' => ucwords(strtolower($this->input->post('company'))),
                    'dob' => $dob_long,
                    'gender' => $this->input->post('gender'),
                    'phone' => $this->input->post('phone'),
                    'mobile' => $this->input->post('mobile'),
                    'address' => ucwords(strtolower($this->input->post('address')))
                    );
                    $this->Accueil_m->register_profile($data_profile);

//                    $this->Accueil_m->get_user($email,  md5($password));
//                    $this->session->set_userdata('display_name', $display_name);
//                    $this->session->set_userdata('group_id', '3');
//                    $this->session->set_userdata('user_id', $user_id);

                    //send mail
                    $From = 'administrator@lehu.com';
                    $this->email->from($From, 'Lehu');
                    $this->email->to($this->input->post('reg_email'));
                    $this->email->subject("s'inscrire dans Lehu");
                     $message = 'Hello ' . $this->input->post('display_name').".<p> - Vous, ou quelqu'un en utilisant cette adresse e-mail pour vous inscrire sur le site: Lehu.</p>
                           <p> - Faire en sorte que vos abonnés, s'il vous plaît cliquer ici pour valider: <a href='". site_url('accueil/activate_user').'/'.$user_id."'>Confirmer</a> et connexion </p>
                              Cordialement,";
                    $this->email->message($message);

//                    echo $this->input->post('reg_email');
//                    echo $this->input->post('display_name');
//                    echo $message;die;
                    $this->email->send();
                    //end send

                    $this->load->view('accueil/register_success');
                }
            } else {
                $this->load->view('accueil/register',$data);
            }
        } else {
            $this->load->view('accueil/register',$data);
        }
    }

    function is_correct_captcha($captcha)
    {
        $expiration = time()-1800;
        $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
        $binds = array($captcha, $this->input->ip_address(), $expiration);
        $query = $this->db->query($sql, $binds);
        $row = $query->row();

        if ($row->count == 0)
        {
            $this->form_validation->set_message('is_correct_captcha','Please enter correct word in the picture!');
            return FALSE;
        }
        return TRUE;        
    }

    function check_exist_email() {
        $email = $this->input->post('reg_email');
        $query = $this->Accueil_m->get_exist_email($email);
        if ($query->num_rows() > 0) {
            $this->form_validation->set_message('check_exist_email', 'The email address was exist');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function check_exist_username() {
        $username = $this->input->post('user_name');
        $query = $this->Accueil_m->get_exist_username($username);
        if ($query->num_rows() > 0) {
            $this->form_validation->set_message('check_exist_username', 'The user name was exist');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function login() {
        $utc = now();
        //validate login form//
        if ($this->input->post('submit')) {
            $formVal = array(array(
            'field' => 'email',
            'Label' => 'Email',
            'rules' => 'required|valid_email'
            ),
            array(
            'field' => 'pass',
            'Label' => 'Password',
            'rules' => 'required'
            )
            );
            $this->form_validation->set_rules($formVal);
            //------------------//
            if ($this->form_validation->run() === TRUE) {
                $email = $this->input->post('email');
                $password = md5($this->input->post('pass'));
                $query1 = $this->Admin_m->get_deactivate_user($email,$password);
                if($query1->num_rows > 0){
                    $aRow = $query1->row();
                    if($aRow -> active == 0){
                        $this->_data['login_error'] = "Account is banned!!!";
                        $this->display_view('accueil/accueil');
                    }else{
                        $query = $this->Accueil_m->get_user($email, $password);
                        if ($query->num_rows > 0) {
                            $login_user = $query->row();
                            $data = array('last_login' => $utc);
                            $this->Accueil_m->change_login_time($data, $login_user->id);
                            $this->session->set_userdata('display_name', $login_user->display_name);
                            $this->session->set_userdata('group_id', $login_user->group_id);
                            $this->session->set_userdata('user_id', $login_user->id);
                            $nav_link = $this->session->userdata('smart_navigate_url')?$this->session->userdata('smart_navigate_url'):base_url();
                            redirect($nav_link);
                        } else {
                            $this->_data['login_error'] = "Wrong email or password, Please try again";
                            $this->display_view('accueil/accueil');
                        }
                    }
                }else{
                    $this->_data['login_error'] = "Wrong email or password, Please try again";
                    $this->display_view('accueil/accueil');
                }
            } else {
                $this->_data['validate_error'] = TRUE;
                $this->display_view('accueil/accueil');
            }
        } else {
            $this->display_view('accueil/accueil');
        }
    }

    function logout() {
        $this->session->unset_userdata('user_id');
        $nav_link = $this->session->userdata('smart_navigate_url')?$this->session->userdata('smart_navigate_url'):base_url();
        redirect($nav_link);
    }

    function list_news() {
        $per_page = $this->uri->segment(4) != '' ? $this->uri->segment(4) : 5;
        $off_set = $this->uri->segment(5) != '' ? $this->uri->segment(5) : 0;
        $config['base_url'] = base_url() . 'index.php/accueil_actualite/actualite/list_news/' . $per_page . '/';
        $this->session->set_userdata('smart_navigate_url',  site_url('accueil/list_news'));
        $config['uri_segment'] = 5;
        $config['per_page'] = '5';
        $config['total_rows'] = $this->db->count_all('lehu_actualite');
        if ($config['total_rows'] == $off_set && $off_set > 0) {
            $off_set = $off_set - $per_page;
        }
        $this->_data['actualite'] = $this->Accueil_m->get_all_news($per_page, $off_set);
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();
        $this->_data['page_title'] = "Liste actualite";
        $this->_data['per_page'] = $per_page;
        $this->_data['off_set'] = $off_set;
        $this->display_view('accueil/liste_actualite');
    }

    function news_detail($id) {
        $this->_data['posted_author'] = $this->Accueil_m->get_posted_author($id);
        $query = $this->_data['news_detail'] = $this->Accueil_m->get_news_detail($id);
        $this->session->set_userdata('smart_navigate_url',  site_url('accueil/news_detail'.'/'.$id));
        $this->display_view('accueil/news_detail');
        $row = $query->row();
        $views = $row->hits;
        $count_views = $views + 1;
        $data = array('hits' => $count_views);
        $this->Accueil_m->update_news_view($data, $id);
    }

    function edit_profile($id=0) {
        $birthday = $this->input->post('birth_year') . '-' . $this->input->post('birth_month') . '-' . $this->input->post('birth_date') . ' ' . '06:00';
        $dob_long = human_to_unix($birthday);
        $admin = $this->Admin_m->get_admin_details($id);
        $this->_data['admin_data'] = $admin;

        $this->_data['erreur'] = "";
        $config = array(
        array(
        'field' => 'display_name',
        'label' => 'Display name',
        'rules' => 'required'
        ),
        array(
        'field' => 'first_name',
        'label' => 'First name',
        'rules' => 'required'
        ),
        array(
        'field' => 'last_name',
        'label' => 'Last name',
        'rules' => 'required'
        ),
        array(
        'field' => 'company',
        'label' => 'Company',
        'rules' => 'required'
        ),
        array(
        'field' => 'address',
        'label' => 'address',
        'rules' => 'required'
        ),
        array(
        'field' => 'phone',
        'Label' => 'Phone number',
        'rules' => 'min_length[10]'
        ),
        array(
        'field' => 'mobile',
        'Label' => 'Mobile number',
        'rules' => 'min_length[10]'
        )
        );
        $this->form_validation->set_rules($config);
        if ($this->input->post('submit')) {
            $image_path = './assets/avatar';
            $thumb_path = $image_path . '/images';
            $config = array(
            'allowed_types' => "jpg|jpeg|gif|png",
            'upload_path' => $image_path,
            'max_size' => 10000,
            'encrypt_name' =>TRUE
            );
            $this->_data['page_title'] = "Uploading...";
            $this->load->library('upload', $config);

            if ($this->upload->do_upload()) {
                $upload_info = $this->upload->data();
                $config = array(
                'source_image' => $upload_info['full_path'], //get original image
                'new_image' => $thumb_path, //save as new image //need to create thumbs first
                'maintain_ratio' => true,
                'width' => 300,
                'height' => 200
                );
                $this->load->library('image_lib', $config); //load library
                $this->image_lib->resize(); //do whatever specified in config
                delete_pro_file($upload_info['full_path']);

                if ($this->form_validation->run()) {
                    $data = array(
                    'display_name' => $this->input->post('display_name'),
                    'first_name' => $this->input->post('first_name'),
                    'last_name' => $this->input->post('last_name'),
                    'company' => $this->input->post('company'),
                    'gender' => $this->input->post('gender'),
                    'dob' => $dob_long,
                    'phone' => $this->input->post('phone'),
                    'mobile' => $this->input->post('mobile'),
                    'address' => $this->input->post('address'),
                    'gravatar' => $upload_info['file_name']
                    );
                    $this->Admin_m->edit_profile($data, $id);
                    $this->session->set_userdata('display_name',$this->input->post('display_name'));
                    $nav_link = $this->session->userdata('smart_navigate_url')?$this->session->userdata('smart_navigate_url'):base_url();
                    redirect($nav_link);
                } else {
                    $this->display_view('accueil/edit_profile');
                }
            } else {
                if ($this->form_validation->run()) {
                    $data = array(
                    'display_name' => $this->input->post('display_name'),
                    'first_name' => $this->input->post('first_name'),
                    'last_name' => $this->input->post('last_name'),
                    'company' => $this->input->post('company'),
                    'gender' => $this->input->post('gender'),
                    'dob' => $dob_long,
                    'phone' => $this->input->post('phone'),
                    'mobile' => $this->input->post('mobile'),
                    'address' => $this->input->post('address')
                    );
                    $this->Admin_m->edit_profile($data, $id);
                    $this->session->set_userdata('display_name', $this->input->post('display_name'));
                    $nav_link = $this->session->userdata('smart_navigate_url')?$this->session->userdata('smart_navigate_url'):base_url();
                    redirect($nav_link);
                } else {
                    $this->display_view('accueil/edit_profile');
                }
            }
        } else {
            $this->display_view('accueil/edit_profile');
        }
    }

    function change_pass($id) {
        $this->_data['erreur'] = "";

        $config = array(
        array(
        'field' => 'apass',
        'label' => 'Ancien mot de passe',
        'rules' => 'required|md5'
        ),
        array(
        'field' => 'npass',
        'label' => 'Nouveau mot de passe',
        'rules' => 'required|matches[confirm_npass]|md5'
        ),
        array(
        'field' => 'confirm_npass',
        'label' => 'Confirmation du mot de passe',
        'rules' => 'required|md5'
        )
        );
        $this->form_validation->set_rules($config);
        if ($this->form_validation->run()) {
            $pass = $this->input->post('apass');
            $query = $this->Admin_m->is_password($pass, $id);
            if ($query) {
                $data = array('password' => $this->input->post('npass'));
                $query = $this->Admin_m->change_pass($data, $id);
                $nav_link = $this->session->userdata('smart_navigate_url')?$this->session->userdata('smart_navigate_url'):base_url();
                redirect($nav_link);
            } else {
                $this->_data['erreur'] = "Mot de passe incorrect";
                $this->display_view('accueil/change_pass');
            }
        }else
            $this->display_view('accueil/change_pass');
    }

    function contact(){
        $configcontact = array(
        array('field' => 'ctfirstname',
        'label' => 'First name',
        'rules' => 'required|xss_clean'
        ),
        array('field' => 'ctlastname',
        'label' => 'Last name',
        'rules' => 'required|xss_clean'
        ),
        array('field' => 'ctemail',
        'label' => 'Email',
        'rules' => 'required|valid_email|xss_clean'
        ),
        array('field' => 'ctmessage',
        'label' => 'Message',
        'rules' => 'required|xss_clean'
        )

        );
        $this->form_validation->set_rules($configcontact);

        if($this->input->post('sendmessage')){
            if($this->form_validation->run() === TRUE){
                $data = array(
                'id'          => '',
                'firstname'   => $this->input->post('ctfirstname'),
                'lastname'    => $this->input->post('ctlastname'),
                'email'       => $this->input->post('ctemail'),
                'message'     => $this->input->post('ctmessage')

                );
                $this->Accueil_m->insert_contact_infor($data);
                $this->display_view("accueil/contact/contactsuccess");
            } else{
                $this->display_view("accueil/contact/contact");
            }

        } else{
            $this->display_view("accueil/contact/contact");
        }
    }

    function propos() {
        $this->_data['erreur'] = "";
        $propos = $this->Admin_m->get_propos();
        $this->_data['propos_client'] = $propos;

        $this->display_view('accueil/propos');

    }

    function forgot_pass(){
        //echo random_string('alnum', 16);die;
        $config = array(
        array(
        'field' => 'forgot_email',
        'label' => 'Your email',
        'rules' => 'required|valid_email'
        )
        );
        $this->form_validation->set_rules($config);
        $config['charset'] = 'utf-8';
        $config['wordwrap'] = TRUE;
        $config['mailtype'] = 'html';

        $this->email->initialize($config);
        if($this->input->post('submit')){
            if($this->form_validation->run()){
                $temp_pass = random_string('alnum',16);
                $email = $this->input->post('forgot_email');
                
                $account_info = $this->Accueil_m->get_account_infor_by_email($email);
                if($account_info->num_rows()>0){
                    $account = $account_info->row();
                    $data = array(
                    'password'=>md5($temp_pass)
                    );
                    if($this->Accueil_m->update_temp_pass($email,$data)>0){
                        $this->email->from('administrator@lehu.com', 'Lehu');
                        $this->email->to($email);
                        $this->email->subject('Mot de passe de récupération');
                        $message = 'Hello '.$account->username.'<p> Please use following account and temporary pass to login at lehu:</p>  <p>+ email for logging in: '.$account->email.'</p><p>+ temporary pass: '.$temp_pass.'</p>';
                        $this->email->message($message);
                        if($this->email->send()){
                            $this->_data['error'] = "Un email vous a été envoyé !";
                           $this->display_view('accueil/forgot_pass');
                        } else{
                            $this->_data['error'] = "Votre email n'est pas valide";
                            $this->display_view('accueil/forgot_pass');    
                        }
                    }
                } else{
                    $this->_data['error'] = "votre e-mail n'a pas été enregistré";
                    $this->display_view('accueil/forgot_pass');
                }
            } else{
                $this->display_view('accueil/forgot_pass');
            }
        } else{
            $this->display_view('accueil/forgot_pass');
        }
    }

    function detail_card_vip() {
        $query = $this->Accueil_m->get_card_vip();
        $this->_data['detail_card_vip'] = $query;
        $this->_data['page_title'] = "CARD VIP";
        $nav_link = $this->session->set_userdata('smart_navigate_url',  site_url('accueil/detail_card_vip'));
        $this->display_view('accueil/detail_card_vip');
    }

    function activate_user($id) {
        $this->Admin_m->activate_user($id);
        $this->display_view('accueil/accueil');
    }

}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */